const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const path = require('path')
const conf = require('./config/projectConfig')
const theme = require('./src/sfs-example/theme')
const isProduction = process.env.NODE_ENV !== 'development'

const productionGzipExtensions = ['js', 'css', 'html']
const Version = 'V1.0'
const Timestamp = new Date().getTime()
function resolve(dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  outputDir: 'dist/' + conf.projectName, // 构建输出目录
  productionSourceMap: false,
  lintOnSave: false,
  publicPath: '/',
  pages: conf.pages,
  css: {
    loaderOptions: {
      less: {
        // 默认主题:default 紫色主题:purple
        modifyVars: theme[conf.themeValue],
        javascriptEnabled: true,
      },
    },
  },
  configureWebpack: {
    resolve: {
      alias: {
        '@': resolve('src'),
      },
    },
    devServer: {
      historyApiFallback: {
        verbose: true,
        rewrites: [{ from: /^index/, to: '/index.html' }],
      },
    },
  },
  // chainWebpack: (config) => {
  //   config.entry('main').add('babel-polyfill')
  //   config.module
  //     .rule('images')
  //     .use('image-webpack-loader')
  //     .loader('image-webpack-loader')
  //     .options({ bypassOnDebug: true })
  //     .end()
  //   config
  //     .plugin('html')
  //     .use(HtmlWebpackPlugin)
  //     .tap((args) => {
  //       if (isProduction || devNeedCdn) args[0].cdn = cdn
  //       return args
  //     })
  //   // 移除打包后 index.html 所有打包好的文件都预加载行为
  //   config.plugins.delete('preload')
  //   config.plugins.delete('prefetch')
  // },

  configureWebpack: (config) => {
    // if (isProduction || devNeedCdn) config.externals = cdn.externals
    if (isProduction) {
      config.plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            compress: {
              drop_debugger: true,
              drop_console: true,
              pure_funcs: ['console.log'],
            },
            warnings: false,
          },
          sourceMap: false,
          parallel: true,
        }),
      )

      config.plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 20480,
          minRatio: 0.8,
        }),
      )
      //打包生成的文件
      config.output.filename = `js/[name].${Version}.${Timestamp}.js`
      config.output.chunkFilename = `js/[name].${Version}.${Timestamp}.js`
    }
  },
}
